<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="MongoDB," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
MongoDB 是一个介于关系数据库和非关系数据库之间的产品，是非关系数据库当中功能最丰富，最像关系数据库的

什么是MongoDB?MongoDB 是由C++语言编写的，是一个基于分布式文件存储的开源数据库系统。
在高负载的情况下，添加更多的节点，可以保证服务器性能">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB 学习(一)">
<meta property="og:url" content="https://zitongchen.github.io/2017/03/20/MongoDB学习(一)/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
MongoDB 是一个介于关系数据库和非关系数据库之间的产品，是非关系数据库当中功能最丰富，最像关系数据库的

什么是MongoDB?MongoDB 是由C++语言编写的，是一个基于分布式文件存储的开源数据库系统。
在高负载的情况下，添加更多的节点，可以保证服务器性能">
<meta property="og:updated_time" content="2017-03-20T14:22:57.110Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB 学习(一)">
<meta name="twitter:description" content="MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
MongoDB 是一个介于关系数据库和非关系数据库之间的产品，是非关系数据库当中功能最丰富，最像关系数据库的

什么是MongoDB?MongoDB 是由C++语言编写的，是一个基于分布式文件存储的开源数据库系统。
在高负载的情况下，添加更多的节点，可以保证服务器性能">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/03/20/MongoDB学习(一)/"/>





  <title> MongoDB 学习(一) | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/03/20/MongoDB学习(一)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                MongoDB 学习(一)
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-03-20T00:00:00+08:00">
                2017-03-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/MongoDB/" itemprop="url" rel="index">
                    <span itemprop="name">MongoDB</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/03/20/MongoDB学习(一)/" class="leancloud_visitors" data-flag-title="MongoDB 学习(一)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。</p>
<p>MongoDB 是一个介于关系数据库和非关系数据库之间的产品，是非关系数据库当中功能最丰富，最像关系数据库的</p>
</blockquote>
<h2 id="什么是MongoDB"><a href="#什么是MongoDB" class="headerlink" title="什么是MongoDB?"></a>什么是MongoDB?</h2><p>MongoDB 是由C++语言编写的，是一个基于分布式文件存储的开源数据库系统。</p>
<p>在高负载的情况下，添加更多的节点，可以保证服务器性能。</p>
<p>MongoDB 旨在为WEB应用提供可扩展的高性能数据存储解决方案。</p>
<p>MongoDB 将数据存储为一个文档，数据结构由键值(key=&gt;value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档，数组及文档数组</p>
<figure class="highlight"><table><tr><td class="code"><pre><div class="line"></div><div class="line">&#123;</div><div class="line">  name: 'Tony',    //field:value</div><div class="line">  age: 22,         //field:value</div><div class="line">  groups: ['news','sport'] //field:value</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="MongoDB的操作"><a href="#MongoDB的操作" class="headerlink" title="MongoDB的操作"></a>MongoDB的操作</h2><h3 id="帮助"><a href="#帮助" class="headerlink" title="帮助"></a>帮助</h3><p><code>help</code>提示db中有那些操作</p>
<p><code>db.help()</code>提示db有那些方法使用及如何使用</p>
<p><code>db.COLLECTION_NAME.help()</code>提示db的集合有那些方法以及如何使用</p>
<h3 id="MongoDB-创建数据库"><a href="#MongoDB-创建数据库" class="headerlink" title="MongoDB 创建数据库"></a>MongoDB 创建数据库</h3><p>语法:</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">use DATABASE_NAME</div></pre></td></tr></table></figure>
<p>创建指定名称的数据库，若是数据库存在则切换到指定的数据库，否则创建新的数据库</p>
<p>实例：</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt;use demo</div><div class="line">switched to db demo</div></pre></td></tr></table></figure>
<p>在MongoDB中查询存在的数据库的命令为<code>show dbs</code>,使用<code>use</code>命令创建数据库时，若数据库里面没有数据使用<code>show dbs</code>是无法显示创建的数据库的，只有该数据库里面有数据才会显示该数据库，所以可以理解为若数据库里面没有数据则不存在该数据库。</p>
<h3 id="MongoDB删除数据库"><a href="#MongoDB删除数据库" class="headerlink" title="MongoDB删除数据库"></a>MongoDB删除数据库</h3><p>删除数据库要<code>切换到该数据库</code>，然后使用<code>db.dropDatabase()</code>命令删除该数据库</p>
<p>显示数据库中的集合使用<code>show tables</code>命令</p>
<p>删除集合也是要<code>切换到该数据库</code>,然后使用<code>db.collection.drop()</code>命令删除该数据库下名为<code>collection</code>的集合(即传统数据库中的表)</p>
<h3 id="MongoDB的增删改查"><a href="#MongoDB的增删改查" class="headerlink" title="MongoDB的增删改查"></a>MongoDB的增删改查</h3><h4 id="插入文档（即传统数据库中的插入数据）"><a href="#插入文档（即传统数据库中的插入数据）" class="headerlink" title="插入文档（即传统数据库中的插入数据）"></a>插入文档（即传统数据库中的插入数据）</h4><p>mongodb的shell同时是一个js的编译器，所以在shell上面可以编写js代码</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">// 插入文档的语法：db.COLLECTION_NAME.insert(document)</span></div><div class="line">&gt; use test  <span class="comment">//使用test数据库</span></div><div class="line">switched to db test</div><div class="line"></div><div class="line">&gt; db.person.insert(&#123;<span class="string">"name"</span>:<span class="string">"Tony"</span>,<span class="string">"age"</span>:<span class="number">22</span>&#125;)  <span class="comment">//创建person集合并插入一个文档</span></div><div class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</div><div class="line"></div><div class="line">&gt; <span class="keyword">var</span> person = &#123;<span class="string">"name"</span>:<span class="string">"czt"</span>,<span class="string">"age"</span>:<span class="number">21</span>&#125;  <span class="comment">//mongodb的shell是支持js的，所以可以创建js对象再进行插入</span></div><div class="line">&gt; db.person.insert(person)</div><div class="line">WriteResult(&#123; <span class="string">"nInserted"</span> : <span class="number">1</span> &#125;)</div></pre></td></tr></table></figure>
<h4 id="find操作"><a href="#find操作" class="headerlink" title="find操作"></a>find操作</h4><p><code>db.COLLECTION_NAME.find()</code>表示查找所以数据，但数据量很大的时候在shell中只返回20条记录</p>
<p><code>db.COLLECTION_NAME.findOne()</code>表示查询一条数据</p>
<p><code>db.COLLECTION_NAME.find().pretty()</code>表示格式输出查询信息</p>
<p><code>db.COLLECTION_NAME.find({&quot;field&quot;:&quot;value&quot;})</code>里面的参数表示按照条件来查询，相当于传统数据库中的where</p>
<p><code>_id</code>这个字段是数据库默认给我们加的GUID，目的就是保证数据的唯一性</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find()</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">22</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div><div class="line"></div><div class="line">&gt; db.person.find().pretty()</div><div class="line">&#123;</div><div class="line">        <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>),</div><div class="line">        <span class="string">"name"</span> : <span class="string">"Tony"</span>,</div><div class="line">        <span class="string">"age"</span> : <span class="number">22</span></div><div class="line">&#125;</div><div class="line"></div><div class="line">&gt; db.person.find(&#123;<span class="string">"name"</span>:<span class="string">"Tony"</span>&#125;).pretty()</div><div class="line">&#123;</div><div class="line">        <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>),</div><div class="line">        <span class="string">"name"</span> : <span class="string">"Tony"</span>,</div><div class="line">        <span class="string">"age"</span> : <span class="number">22</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>MongoDB文档中<code>值为数字类型</code>的字段作为查询条件</p>
<table>
<thead>
<tr>
<th style="text-align:center">操作</th>
<th style="text-align:center">格式</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">==</td>
<td style="text-align:center">｛key:value｝</td>
</tr>
<tr>
<td style="text-align:center">&lt;</td>
<td style="text-align:center">{key:{$lt:value}}</td>
</tr>
<tr>
<td style="text-align:center">&lt;=</td>
<td style="text-align:center">{key:{$lte:value}}</td>
</tr>
<tr>
<td style="text-align:center">&gt;</td>
<td style="text-align:center">{key:{$gt:value}}</td>
</tr>
<tr>
<td style="text-align:center">&gt;=</td>
<td style="text-align:center">{key:{$gte:value}}</td>
</tr>
<tr>
<td style="text-align:center">!=</td>
<td style="text-align:center">{key:{$ne:value}}</td>
</tr>
</tbody>
</table>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find(&#123;<span class="string">"age"</span>:<span class="number">21</span>&#125;) <span class="comment">//年龄==21</span></div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div><div class="line"></div><div class="line">&gt; db.person.find(&#123;<span class="string">"age"</span>:&#123;<span class="attr">$lt</span>:<span class="number">40</span>&#125;&#125;) <span class="comment">///年龄&lt;40</span></div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">33</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div></pre></td></tr></table></figure>
<p>AND条件</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//and条件查询格式</span></div><div class="line">db.COLLECTION_NAME.find(&#123;<span class="attr">key1</span>:value1,<span class="attr">key2</span>:value2&#125;)</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find(&#123;<span class="string">"name"</span>:<span class="string">"Tony"</span>,<span class="string">"age"</span>:<span class="number">21</span>&#125;) <span class="comment">//查询不到该条件的文档</span></div><div class="line">&gt; db.person.find(&#123;<span class="string">"name"</span>:<span class="string">"Tony"</span>,<span class="string">"age"</span>:<span class="number">33</span>&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">33</span> &#125;</div></pre></td></tr></table></figure>
<p>OR条件</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//or条件查询格式</span></div><div class="line">db.COLLECTION_NAME.find(</div><div class="line">  &#123;<span class="attr">$or</span>:[</div><div class="line">    &#123;<span class="attr">key1</span>:value1&#125;,&#123;<span class="attr">key2</span>:value2&#125;</div><div class="line">  ]&#125;)</div><div class="line"><span class="comment">//and 和 or的联合查询</span></div><div class="line"><span class="keyword">do</span>.COLLECTION_NAME.find(&#123;<span class="attr">key1</span>:value1,<span class="attr">$or</span>:[&#123;<span class="attr">key2</span>:value2&#125;,&#123;<span class="attr">key3</span>:value3&#125;]&#125;)</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find(&#123;<span class="attr">$or</span>:[&#123;<span class="string">"name"</span>:<span class="string">"Tony"</span>&#125;,&#123;<span class="string">"age"</span>:<span class="number">21</span>&#125;]&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">33</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div></pre></td></tr></table></figure>
<p>In,Nin条件</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find(&#123;<span class="string">"name"</span>:&#123;<span class="attr">$in</span>:[<span class="string">"Tony"</span>,<span class="string">"czt"</span>]&#125;&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">33</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div><div class="line"><span class="comment">//nin时没有查询到文档</span></div><div class="line">&gt; db.person.find(&#123;<span class="string">"name"</span>:&#123;<span class="attr">$nin</span>:[<span class="string">"Tony"</span>,<span class="string">"czt"</span>]&#125;&#125;)</div><div class="line">&gt;</div></pre></td></tr></table></figure>
<p>在mongodb中还有一个特殊的匹配，那就是<code>正则表格式</code>,应为shell是js的编译器所以支持js的正则表达式</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find(&#123;<span class="string">"name"</span>:<span class="regexp">/^T/</span>&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">33</span> &#125;</div></pre></td></tr></table></figure>
<p>Limit 与Skip方法</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//limit()方法的格式,limit表示在数据库中读取指定数量的记录</span></div><div class="line">db.COLLECTION_NAME.find().limit(NUMBER)</div><div class="line"><span class="comment">//skip()方法格式,skip表示跳过NUMBER条数据读取记录</span></div><div class="line">db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find().skip(<span class="number">10</span>).limit(<span class="number">10</span>)  <span class="comment">//跳过10条记录后再读取10记录</span></div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7024"</span>), <span class="string">"name"</span> : <span class="string">"czt10"</span>, <span class="string">"num"</span> : <span class="number">6</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7025"</span>), <span class="string">"name"</span> : <span class="string">"czt11"</span>, <span class="string">"num"</span> : <span class="number">8</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7026"</span>), <span class="string">"name"</span> : <span class="string">"czt12"</span>, <span class="string">"num"</span> : <span class="number">9</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7027"</span>), <span class="string">"name"</span> : <span class="string">"czt13"</span>, <span class="string">"num"</span> : <span class="number">6</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7028"</span>), <span class="string">"name"</span> : <span class="string">"czt14"</span>, <span class="string">"num"</span> : <span class="number">6</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7029"</span>), <span class="string">"name"</span> : <span class="string">"czt15"</span>, <span class="string">"num"</span> : <span class="number">7</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce702a"</span>), <span class="string">"name"</span> : <span class="string">"czt16"</span>, <span class="string">"num"</span> : <span class="number">3</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce702b"</span>), <span class="string">"name"</span> : <span class="string">"czt17"</span>, <span class="string">"num"</span> : <span class="number">15</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce702c"</span>), <span class="string">"name"</span> : <span class="string">"czt18"</span>, <span class="string">"num"</span> : <span class="number">6</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce702d"</span>), <span class="string">"name"</span> : <span class="string">"czt19"</span>, <span class="string">"num"</span> : <span class="number">8</span> &#125;</div><div class="line"><span class="comment">//limit()跟skip()位置调换结果一样</span></div><div class="line">&gt; db.person.find().limit(<span class="number">10</span>).skip(<span class="number">10</span>)</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7024"</span>), <span class="string">"name"</span> : <span class="string">"czt10"</span>, <span class="string">"num"</span> : <span class="number">6</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7025"</span>), <span class="string">"name"</span> : <span class="string">"czt11"</span>, <span class="string">"num"</span> : <span class="number">8</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7026"</span>), <span class="string">"name"</span> : <span class="string">"czt12"</span>, <span class="string">"num"</span> : <span class="number">9</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7027"</span>), <span class="string">"name"</span> : <span class="string">"czt13"</span>, <span class="string">"num"</span> : <span class="number">6</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7028"</span>), <span class="string">"name"</span> : <span class="string">"czt14"</span>, <span class="string">"num"</span> : <span class="number">6</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7029"</span>), <span class="string">"name"</span> : <span class="string">"czt15"</span>, <span class="string">"num"</span> : <span class="number">7</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce702a"</span>), <span class="string">"name"</span> : <span class="string">"czt16"</span>, <span class="string">"num"</span> : <span class="number">3</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce702b"</span>), <span class="string">"name"</span> : <span class="string">"czt17"</span>, <span class="string">"num"</span> : <span class="number">15</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce702c"</span>), <span class="string">"name"</span> : <span class="string">"czt18"</span>, <span class="string">"num"</span> : <span class="number">6</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce702d"</span>), <span class="string">"name"</span> : <span class="string">"czt19"</span>, <span class="string">"num"</span> : <span class="number">8</span> &#125;</div></pre></td></tr></table></figure>
<p>sort()方法</p>
<p>mongodb中使用sort()函数对数据进行排序，key为排序方式，1为升序排序，-1为降序排序</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">db.COLLECTION_NAME.find().sort(&#123;<span class="attr">key</span>:<span class="number">1</span>&#125;)</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find().limit(<span class="number">5</span>).sort(&#123;<span class="string">"num"</span>:<span class="number">1</span>&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701a"</span>), <span class="string">"name"</span> : <span class="string">"czt0"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701b"</span>), <span class="string">"name"</span> : <span class="string">"czt1"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701c"</span>), <span class="string">"name"</span> : <span class="string">"czt2"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701f"</span>), <span class="string">"name"</span> : <span class="string">"czt5"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7031"</span>), <span class="string">"name"</span> : <span class="string">"czt23"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div></pre></td></tr></table></figure>
<p>正常情况下无论limit,sort位置怎么变化，都是先执行sort()方法然后执行limit方法</p>
<h4 id="update操作"><a href="#update操作" class="headerlink" title="update操作"></a>update操作</h4><p>mongodb的update()函数有5个参数</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//语法格式</span></div><div class="line">db.COLLECTION_NAME.update(</div><div class="line">	&lt;query&gt;,  //更新的查询条件</div><div class="line">	&lt;update&gt;, //更新的内容</div><div class="line">	&#123;</div><div class="line">      upsert: &lt;boolean&gt;, //可选，若更新文档存在则更新文档，不存在则插入文档,默认false</div><div class="line">      multi: &lt;boolean&gt;, //可选，默认false,是否批量更新符合条件的文档</div><div class="line">      writeConcern: &lt;boolean&gt; //可选，抛出异常的级别</div><div class="line">	&#125;</div><div class="line">)</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.update(&#123;<span class="string">"name"</span>:<span class="string">"jack"</span>&#125;,&#123;<span class="string">"age"</span>:<span class="number">32</span>&#125;)</div><div class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">0</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">0</span> &#125;) </div><div class="line"><span class="comment">//没有修改，应为不存在name==jack的文档，同时upsert默认为false所以无法作为新文档插入</span></div><div class="line">&gt; db.person.find()</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">22</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div><div class="line"></div><div class="line"><span class="comment">//把upsert设置为true时，若不存在符合查询条件时，会把更新内容（不含查询条件）作为新文档插入到集合中</span></div><div class="line">&gt; db.person.update(&#123;<span class="string">"name"</span>:<span class="string">"jack"</span>&#125;,&#123;<span class="string">"age"</span>:<span class="number">32</span>&#125;,&#123;<span class="attr">upsert</span>:<span class="literal">true</span>&#125;)</div><div class="line">WriteResult(&#123;</div><div class="line">        <span class="string">"nMatched"</span> : <span class="number">0</span>,</div><div class="line">        <span class="string">"nUpserted"</span> : <span class="number">1</span>,</div><div class="line">        <span class="string">"nModified"</span> : <span class="number">0</span>,</div><div class="line">        <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf35cebf713f26b8c0d9b8"</span>)</div><div class="line">&#125;)</div><div class="line">&gt; db.person.find()</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">22</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf35cebf713f26b8c0d9b8"</span>), <span class="string">"age"</span> : <span class="number">32</span> &#125;</div><div class="line"></div><div class="line"><span class="comment">//$set更新</span></div><div class="line">&gt; db.person.update(&#123;<span class="string">"name"</span>:<span class="string">"Tony"</span>&#125;,&#123;<span class="attr">$set</span>:&#123;<span class="string">"age"</span>:<span class="number">33</span>&#125;&#125;)</div><div class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</div><div class="line">&gt; db.person.find()</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">33</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf35cebf713f26b8c0d9b8"</span>), <span class="string">"age"</span> : <span class="number">32</span> &#125;</div><div class="line"></div><div class="line"><span class="comment">//$inc（increase的缩写）更新 是在原有的基础上修改，Tony的年龄由 33 变成了 43</span></div><div class="line">&gt; db.person.update(&#123;<span class="string">"name"</span>:<span class="string">"Tony"</span>&#125;,&#123;<span class="attr">$inc</span>:&#123;<span class="string">"age"</span>:<span class="number">10</span>&#125;&#125;)</div><div class="line">WriteResult(&#123; <span class="string">"nMatched"</span> : <span class="number">1</span>, <span class="string">"nUpserted"</span> : <span class="number">0</span>, <span class="string">"nModified"</span> : <span class="number">1</span> &#125;)</div><div class="line">&gt; db.person.find()</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">43</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div></pre></td></tr></table></figure>
<h4 id="remove-操作"><a href="#remove-操作" class="headerlink" title="remove()操作"></a>remove()操作</h4><figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//语法格式</span></div><div class="line">db.COLLECTION_NAME.remove(</div><div class="line">	&lt;query&gt;, //(可选)删除文档的条件</div><div class="line">	&#123;</div><div class="line">      justOne:&lt;boolean&gt;, //(可选)若为true和1,则只删除一个文档</div><div class="line">      writeConcern:&lt;document&gt; //(可选)抛出异常的级别</div><div class="line">	&#125;)</div><div class="line"></div><div class="line">db.COLLECTION_NAME.remove(&#123;&#125;) //表示删除所以文档，这个是不可恢复的，谨慎操作哦</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.find()</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">33</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf35cebf713f26b8c0d9b8"</span>), <span class="string">"age"</span> : <span class="number">32</span> &#125;</div><div class="line"><span class="comment">//删除age==32的文档</span></div><div class="line">&gt; db.person.remove(&#123;<span class="string">"age"</span>:<span class="number">32</span>&#125;)</div><div class="line">WriteResult(&#123; <span class="string">"nRemoved"</span> : <span class="number">1</span> &#125;)</div><div class="line">&gt; db.person.find()</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2e78bfb3c1884e23e9da"</span>), <span class="string">"name"</span> : <span class="string">"Tony"</span>, <span class="string">"age"</span> : <span class="number">33</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf2ee1bfb3c1884e23e9db"</span>), <span class="string">"name"</span> : <span class="string">"czt"</span>, <span class="string">"age"</span> : <span class="number">21</span> &#125;</div></pre></td></tr></table></figure>
<h4 id="索引"><a href="#索引" class="headerlink" title="索引"></a>索引</h4><p>索引通常能够极大的提高查询的效率，如果没有索引，MongoDB在读取数据时必须扫描集合中的每个文件并选取那些符合查询条件的记录</p>
<p>这种扫描全集合的查询效率是非常低的，特别在处理大量的数据时，查询可以要花费几十秒甚至几分钟，这对网站的性能是非常致命的</p>
<p>索引是特殊的数据结构，索引存储在一个易于遍历读取的数据集合中，索引是对数据库表中一列或多列的值进行排序的一种结构</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//单字段索引，key的值表示按照升序还是降序建立索引 ,1表示升序，-1表示降序</span></div><div class="line">db.COLLECTION_NAME.ensureIndex(&#123;<span class="attr">key</span>:<span class="number">1</span>&#125;)</div><div class="line"><span class="comment">//多字段索引</span></div><div class="line">db.COLLECTION_NAME.ensureIndex(&#123;<span class="attr">key1</span>:<span class="number">1</span>,<span class="attr">key2</span>:<span class="number">1</span>&#125;)</div><div class="line"><span class="comment">//删除某个索引</span></div><div class="line">db.COLLECTION_NAME.dropIndex(name) <span class="comment">//name索引的名称</span></div><div class="line"><span class="comment">//删除索引索引，但不包含_id索引</span></div><div class="line">db.COLLECTION_NAME.dropIndexes()</div></pre></td></tr></table></figure>
<p>建立索引ensureIndex()可以接受可选参数，<a href="http://www.runoob.com/mongodb/mongodb-indexing.html" target="_blank" rel="external">点击可查询可选参数</a></p>
<p>没有用的索引要删除，索引会降低CUD这三种操作的性能，因为这玩意需要实时维护，所以啥问题都要综合考虑一下</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&gt; db.person.getIndexes() <span class="comment">//集合查询索引方法</span></div><div class="line">[</div><div class="line">        &#123;</div><div class="line">                <span class="string">"v"</span> : <span class="number">2</span>,</div><div class="line">                <span class="string">"key"</span> : &#123;</div><div class="line">                        <span class="string">"_id"</span> : <span class="number">1</span></div><div class="line">                &#125;,</div><div class="line">                <span class="string">"name"</span> : <span class="string">"_id_"</span>,</div><div class="line">                <span class="string">"ns"</span> : <span class="string">"demo.person"</span></div><div class="line">        &#125;,</div><div class="line">        &#123;</div><div class="line">                <span class="string">"v"</span> : <span class="number">2</span>,</div><div class="line">                <span class="string">"key"</span> : &#123;</div><div class="line">                        <span class="string">"name"</span> : <span class="number">1</span>,</div><div class="line">                        <span class="string">"age"</span> : <span class="number">1</span></div><div class="line">                &#125;,</div><div class="line">                <span class="string">"name"</span> : <span class="string">"name_1_age_1"</span>, <span class="comment">//name + age 组成的多字段索引</span></div><div class="line">                <span class="string">"ns"</span> : <span class="string">"demo.person"</span></div><div class="line">        &#125;</div><div class="line">]</div><div class="line"><span class="comment">//删除索引</span></div><div class="line">&gt; db.person.dropIndexes()</div><div class="line">&#123;</div><div class="line">        <span class="string">"nIndexesWas"</span> : <span class="number">2</span>,</div><div class="line">        <span class="string">"msg"</span> : <span class="string">"non-_id indexes dropped for collection"</span>,</div><div class="line">        <span class="string">"ok"</span> : <span class="number">1</span></div><div class="line">&#125;</div><div class="line">&gt; db.person.getIndexes()</div><div class="line">[</div><div class="line">        &#123;</div><div class="line">                <span class="string">"v"</span> : <span class="number">2</span>,</div><div class="line">                <span class="string">"key"</span> : &#123;</div><div class="line">                        <span class="string">"_id"</span> : <span class="number">1</span></div><div class="line">                &#125;,</div><div class="line">                <span class="string">"name"</span> : <span class="string">"_id_"</span>,</div><div class="line">                <span class="string">"ns"</span> : <span class="string">"demo.person"</span></div><div class="line">        &#125;</div><div class="line">]</div></pre></td></tr></table></figure>
<h3 id="MongoDB聚合"><a href="#MongoDB聚合" class="headerlink" title="MongoDB聚合"></a>MongoDB聚合</h3><p>MongoDB中的聚合（aggregate）主要用于处理数据，并返回计算结果，在MongoDB中聚合的方法使用<code>aggregate()</code></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//聚合函数的格式</span></div><div class="line">db.COLLECTION_NAME.aggregate(AGGREGETE_OPERATION)</div></pre></td></tr></table></figure>
<p>创建一个集合<code>col</code>,并把数据插入集合中</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line">&#123;</div><div class="line">   <span class="attr">_id</span>: ObjectId(<span class="number">7</span>df78ad8902c)</div><div class="line">   title: <span class="string">'MongoDB Overview'</span>, </div><div class="line">   <span class="attr">description</span>: <span class="string">'MongoDB is no sql database'</span>,</div><div class="line">   <span class="attr">user</span>: <span class="string">'w3cschool.cc'</span>,</div><div class="line">   <span class="attr">url</span>: <span class="string">'http://www.w3cschool.cc'</span>,</div><div class="line">   <span class="attr">tags</span>: [<span class="string">'mongodb'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</div><div class="line">   <span class="attr">likes</span>: <span class="number">100</span></div><div class="line">&#125;,</div><div class="line">&#123;</div><div class="line">   <span class="attr">_id</span>: ObjectId(<span class="number">7</span>df78ad8902d)</div><div class="line">   title: <span class="string">'NoSQL Overview'</span>, </div><div class="line">   <span class="attr">description</span>: <span class="string">'No sql database is very fast'</span>,</div><div class="line">   <span class="attr">user</span>: <span class="string">'w3cschool.cc'</span>,</div><div class="line">   <span class="attr">url</span>: <span class="string">'http://www.w3cschool.cc'</span>,</div><div class="line">   <span class="attr">tags</span>: [<span class="string">'mongodb'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</div><div class="line">   <span class="attr">likes</span>: <span class="number">10</span></div><div class="line">&#125;,</div><div class="line">&#123;</div><div class="line">   <span class="attr">_id</span>: ObjectId(<span class="number">7</span>df78ad8902e)</div><div class="line">   title: <span class="string">'Neo4j Overview'</span>, </div><div class="line">   <span class="attr">description</span>: <span class="string">'Neo4j is no sql database'</span>,</div><div class="line">   <span class="attr">user</span>: <span class="string">'Neo4j'</span>,</div><div class="line">   <span class="attr">url</span>: <span class="string">'http://www.neo4j.com'</span>,</div><div class="line">   <span class="attr">tags</span>: [<span class="string">'neo4j'</span>, <span class="string">'database'</span>, <span class="string">'NoSQL'</span>],</div><div class="line">   <span class="attr">likes</span>: <span class="number">750</span></div><div class="line">&#125;,</div></pre></td></tr></table></figure>
<p>聚合函数表达式</p>
<table>
<thead>
<tr>
<th style="text-align:center">表达式</th>
<th style="text-align:center">描述</th>
<th style="text-align:center">实例</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">$sum</td>
<td style="text-align:center">计算总和</td>
<td style="text-align:center">db.col.aggregate({$group:{_id:”user”,count:{$sum:”like”}}})</td>
</tr>
<tr>
<td style="text-align:center">$avg</td>
<td style="text-align:center">计算平均值</td>
<td style="text-align:center">db.col.aggregate({$group:{_id:”user”,count:{$avg:”like”}}})</td>
</tr>
<tr>
<td style="text-align:center">$min</td>
<td style="text-align:center">获取集合中的最小值</td>
<td style="text-align:center">db.col.aggregate({$group:{_id:”user”,count:{$min:”like”}}})</td>
</tr>
<tr>
<td style="text-align:center">$max</td>
<td style="text-align:center">获取集合中的最大值</td>
<td style="text-align:center">db.col.aggregate({$group:{_id:”user”,count:{$max:”like”}}})</td>
</tr>
<tr>
<td style="text-align:center">$push</td>
<td style="text-align:center">在结果文档中插入值到一个数组中</td>
<td style="text-align:center">db.col.aggregate({$group:{_id:”user”,URL:{$push:”$url”}}})</td>
</tr>
<tr>
<td style="text-align:center">$addToSet</td>
<td style="text-align:center">在结果文档中插入值到一个数组中，但不创建副本</td>
<td style="text-align:center">db.col.aggregate({$group:{_id:”user”,URL:{$addToSet:”$url”}}})</td>
</tr>
<tr>
<td style="text-align:center">$first</td>
<td style="text-align:center">根据文档的排序获取第一个文档</td>
<td style="text-align:center">db.col.aggregate({$group:{_id:”user”,URL:{$first:”$url”}}})</td>
</tr>
<tr>
<td style="text-align:center">$last</td>
<td style="text-align:center">根据文档排序获取最后一个</td>
<td style="text-align:center">db.col.aggregate({$group:{_id:”user”,URL:{$last:”$url”}}})</td>
</tr>
</tbody>
</table>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//$sum 计算一个作者所拥有的数量 若是$sum:后面跟数字，表示 (数字 * 按组统计的结果)</span></div><div class="line">&gt; db.col.aggregate(&#123;<span class="attr">$group</span>:&#123;<span class="attr">_id</span>:<span class="string">"$user"</span>,<span class="attr">count</span>:&#123;<span class="attr">$sum</span>:<span class="number">1</span>&#125;&#125;&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"Neo4j"</span>, <span class="string">"count"</span> : <span class="number">1</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"w3cschool.cc"</span>, <span class="string">"count"</span> : <span class="number">2</span> &#125;</div><div class="line"><span class="comment">//观察跟上一条命令的不同之处</span></div><div class="line">&gt; db.col.aggregate(&#123;<span class="attr">$group</span>:&#123;<span class="attr">_id</span>:<span class="string">"$user"</span>,<span class="attr">count</span>:&#123;<span class="attr">$sum</span>:<span class="number">2</span>&#125;&#125;&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"Neo4j"</span>, <span class="string">"count"</span> : <span class="number">2</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"w3cschool.cc"</span>, <span class="string">"count"</span> : <span class="number">4</span> &#125;</div><div class="line"></div><div class="line"><span class="comment">//&#123;$sum:"like"&#125; </span></div><div class="line">&gt; db.col.aggregate(&#123;<span class="attr">$group</span>:&#123;<span class="attr">_id</span>:<span class="string">"$user"</span>,<span class="attr">count</span>:&#123;<span class="attr">$sum</span>:<span class="string">"$like"</span>&#125;&#125;&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"Neo4j"</span>, <span class="string">"count"</span> : <span class="number">700</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"w3cschool.cc"</span>, <span class="string">"count"</span> : <span class="number">110</span> &#125;</div><div class="line"></div><div class="line"><span class="comment">//&#123;$push:"$url"&#125;</span></div><div class="line">&gt; db.col.aggregate(&#123;<span class="attr">$group</span>:&#123;<span class="attr">_id</span>:<span class="string">"$user"</span>,<span class="attr">URL</span>:&#123;<span class="attr">$push</span>:<span class="string">"$url"</span>&#125;&#125;&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"Neo4j"</span>, <span class="string">"URL"</span> : [ <span class="string">"http://www.neo4j.cc"</span> ] &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"w3cschool.cc"</span>, <span class="string">"URL"</span> : [ <span class="string">"http://www.w3cschool.cc"</span>, <span class="string">"http://www.w3cschool.cc"</span> ] &#125;</div><div class="line"></div><div class="line"><span class="comment">//&#123;$addToSet:"$url"&#125; 不重复创建数组里面存在的内容，就是把数据放进set类型的数组</span></div><div class="line">&gt; db.col.aggregate(&#123;<span class="attr">$group</span>:&#123;<span class="attr">_id</span>:<span class="string">"$user"</span>,<span class="attr">URL</span>:&#123;<span class="attr">$addToSet</span>:<span class="string">"$url"</span>&#125;&#125;&#125;)</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"Neo4j"</span>, <span class="string">"URL"</span> : [ <span class="string">"http://www.neo4j.cc"</span> ] &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : <span class="string">"w3cschool.cc"</span>, <span class="string">"URL"</span> : [ <span class="string">"http://www.w3cschool.cc"</span> ] &#125;</div></pre></td></tr></table></figure>
<h3 id="聚合-二"><a href="#聚合-二" class="headerlink" title="聚合(二)"></a>聚合(二)</h3><p>聚合操作：count,distinct,group,mapReduce</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">&gt; db.col.count()</div><div class="line">3</div><div class="line">&gt; db.col.distinct(&quot;like&quot;)</div><div class="line">[ 10, 100, 700 ]</div><div class="line">&gt;</div></pre></td></tr></table></figure>
<p>group</p>
<p>在mongodb里面做group操作有点小复杂，不过大家对sql server里面的group比较熟悉的话还是一眼</p>
<p>能看的明白的，其实group操作本质上形成了一种“k-v”模型,好,有了这种思维，</p>
<p>我们来看看如何使用group。</p>
<p>​    下面举的例子就是按照age进行group操作，value为对应age的姓名。下面对这些参数介绍一下：</p>
<p>​       key：  这个就是分组的key，我们这里是对年龄分组。</p>
<p>​       initial: 每组都分享一个”初始化函数“，特别注意：是每一组，比如这个的age=20的value的list分享一个</p>
<p>initial函数，age=22同样也分享一个initial函数。</p>
<p>​       $reduce: 这个函数的第一个参数是当前的文档对象，第二个参数是上一次function操作的累计对象，第一次</p>
<p>为initial中的{”perosn“：[]}。有多少个文档， $reduce就会调用多少次。<code>&lt;待续&gt;</code></p>
<h3 id="管道"><a href="#管道" class="headerlink" title="管道"></a>管道</h3><p>管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。</p>
<p>MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。</p>
<p>表达式：处理输入文档并输出。表达式是无状态的，只能用于计算当前聚合管道的文档，不能处理其它的文档。</p>
<p>这里我们介绍一下聚合框架中常用的几个操作：</p>
<ul>
<li>$project：修改输入文档的结构。可以用来重命名、增加或删除域，也可以用于创建计算结果以及嵌套文档。</li>
<li>$ match：用于过滤数据，只输出符合条件的文档。match使用MongoDB的标准查询操作。</li>
<li>$limit：用来限制MongoDB聚合管道返回的文档数。格式：{$limit:value}</li>
<li>$skip：在聚合管道中跳过指定数量的文档，并返回余下的文档。</li>
<li>$unwind：将文档中的某一个数组类型字段拆分成多条，每条包含数组中的一个值。</li>
<li>$group：将集合中的文档分组，可用于统计结果。</li>
<li>$sort：将输入文档排序后输出。格式：{$sort:{key:value}｝</li>
<li>$geoNear：输出接近某一地理位置的有序文档。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//单一操作</span></div><div class="line">db.COLLECTION_NAME.aggregate(&#123;$name&#125;)/db.COLLECTION_NAME.aggregate([&#123;$name&#125;])</div><div class="line"><span class="comment">//管道多值按照操作顺序进行操作</span></div><div class="line">db.COLLECTION_NAME.aggregate([&#123;$name1&#125;,&#123;$name2&#125;])</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><div class="line"><span class="comment">//$project 表示只显示列出的字段，_id默认显示，不显示可以设置&#123;$project:&#123;_id:0,title:1,user:1&#125;&#125;</span></div><div class="line">&gt; db.col.aggregate(&#123;<span class="attr">$project</span>:&#123;<span class="attr">title</span>:<span class="number">1</span>,<span class="attr">user</span>:<span class="number">1</span>&#125;&#125;).pretty()</div><div class="line">&#123;</div><div class="line">        <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf64debfb3c1884e23e9dc"</span>),</div><div class="line">        <span class="string">"title"</span> : <span class="string">"NoSql overview"</span>,</div><div class="line">        <span class="string">"user"</span> : <span class="string">"w3cschool.cc"</span></div><div class="line">&#125;</div><div class="line">&#123;</div><div class="line">        <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf8147bfb3c1884e23e9dd"</span>),</div><div class="line">        <span class="string">"title"</span> : <span class="string">"MongoDB Overview"</span>,</div><div class="line">        <span class="string">"user"</span> : <span class="string">"w3cschool.cc"</span></div><div class="line">&#125;</div><div class="line">&#123;</div><div class="line">        <span class="string">"_id"</span> : ObjectId(<span class="string">"58cf8193bfb3c1884e23e9de"</span>),</div><div class="line">        <span class="string">"title"</span> : <span class="string">"Neo4j Overview"</span>,</div><div class="line">        <span class="string">"user"</span> : <span class="string">"Neo4j"</span></div><div class="line">&#125;</div><div class="line"><span class="comment">//上文提到过正常情况下是先执行sort再执行limit，利用管道可以按照管道内的顺序执行操作</span></div><div class="line">&gt; db.person.aggregate([&#123;<span class="attr">$limit</span>:<span class="number">10</span>&#125;,&#123;<span class="attr">$sort</span>:&#123;<span class="attr">num</span>:<span class="number">1</span>&#125;&#125;])</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701a"</span>), <span class="string">"name"</span> : <span class="string">"czt0"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701b"</span>), <span class="string">"name"</span> : <span class="string">"czt1"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701c"</span>), <span class="string">"name"</span> : <span class="string">"czt2"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701f"</span>), <span class="string">"name"</span> : <span class="string">"czt5"</span>, <span class="string">"num"</span> : <span class="number">0</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701d"</span>), <span class="string">"name"</span> : <span class="string">"czt3"</span>, <span class="string">"num"</span> : <span class="number">1</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce701e"</span>), <span class="string">"name"</span> : <span class="string">"czt4"</span>, <span class="string">"num"</span> : <span class="number">1</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7022"</span>), <span class="string">"name"</span> : <span class="string">"czt8"</span>, <span class="string">"num"</span> : <span class="number">2</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7020"</span>), <span class="string">"name"</span> : <span class="string">"czt6"</span>, <span class="string">"num"</span> : <span class="number">3</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7023"</span>), <span class="string">"name"</span> : <span class="string">"czt9"</span>, <span class="string">"num"</span> : <span class="number">4</span> &#125;</div><div class="line">&#123; <span class="string">"_id"</span> : ObjectId(<span class="string">"58ce9e2cafb2b24a29ce7021"</span>), <span class="string">"name"</span> : <span class="string">"czt7"</span>, <span class="string">"num"</span> : <span class="number">5</span> &#125;</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MongoDB/" rel="tag"># MongoDB</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/03/18/Chorme使用技巧/" rel="next" title="Chorme使用技巧">
                <i class="fa fa-chevron-left"></i> Chorme使用技巧
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/03/21/MongoDB学习之备份,恢复,监控/" rel="prev" title="MongoDB学习之备份,恢复,监控">
                MongoDB学习之备份,恢复,监控 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是MongoDB"><span class="nav-number">1.</span> <span class="nav-text">什么是MongoDB?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB的操作"><span class="nav-number">2.</span> <span class="nav-text">MongoDB的操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#帮助"><span class="nav-number">2.1.</span> <span class="nav-text">帮助</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MongoDB-创建数据库"><span class="nav-number">2.2.</span> <span class="nav-text">MongoDB 创建数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MongoDB删除数据库"><span class="nav-number">2.3.</span> <span class="nav-text">MongoDB删除数据库</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MongoDB的增删改查"><span class="nav-number">2.4.</span> <span class="nav-text">MongoDB的增删改查</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#插入文档（即传统数据库中的插入数据）"><span class="nav-number">2.4.1.</span> <span class="nav-text">插入文档（即传统数据库中的插入数据）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#find操作"><span class="nav-number">2.4.2.</span> <span class="nav-text">find操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#update操作"><span class="nav-number">2.4.3.</span> <span class="nav-text">update操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#remove-操作"><span class="nav-number">2.4.4.</span> <span class="nav-text">remove()操作</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#索引"><span class="nav-number">2.4.5.</span> <span class="nav-text">索引</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MongoDB聚合"><span class="nav-number">2.5.</span> <span class="nav-text">MongoDB聚合</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#聚合-二"><span class="nav-number">2.6.</span> <span class="nav-text">聚合(二)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#管道"><span class="nav-number">2.7.</span> <span class="nav-text">管道</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
